// XHR解密工具 - 统计面板逻辑
class DecryptionStats {
    constructor() {
        this.stats = {
            totalRequests: 0,
            successfulDecryptions: 0,
            failedDecryptions: 0,
            algorithms: {
                'timestamp-traceid': { name: '雪花算法', count: 0, success: 0, totalTime: 0, lastUsed: null },
                'uuid-based': { name: '冒泡算法', count: 0, success: 0, totalTime: 0, lastUsed: null },
                'custom-logic': { name: '线性算法', count: 0, success: 0, totalTime: 0, lastUsed: null }
            },
            domains: {},
            errors: {},
            timeSeries: []
        };

        this.init();
    }

    // 初始化统计面板
    init() {
        this.loadStats();
        this.updateDisplay();
        this.startAutoRefresh();
    }

    // 记录解密尝试
    recordDecryptionAttempt(algorithm, success, duration, domain, error = null) {
        const timestamp = Date.now();

        // 更新总体统计
        this.stats.totalRequests++;
        if (success) {
            this.stats.successfulDecryptions++;
        } else {
            this.stats.failedDecryptions++;
        }

        // 更新算法统计
        if (this.stats.algorithms[algorithm]) {
            this.stats.algorithms[algorithm].count++;
            this.stats.algorithms[algorithm].totalTime += duration;
            this.stats.algorithms[algorithm].lastUsed = timestamp;

            if (success) {
                this.stats.algorithms[algorithm].success++;
            }
        }

        // 更新域名统计
        if (!this.stats.domains[domain]) {
            this.stats.domains[domain] = {
                requests: 0,
                success: 0,
                algorithms: {}
            };
        }
        this.stats.domains[domain].requests++;
        if (success) {
            this.stats.domains[domain].success++;
        }

        if (!this.stats.domains[domain].algorithms[algorithm]) {
            this.stats.domains[domain].algorithms[algorithm] = 0;
        }
        this.stats.domains[domain].algorithms[algorithm]++;

        // 记录错误
        if (error) {
            const errorType = this.categorizeError(error);
            if (!this.stats.errors[errorType]) {
                this.stats.errors[errorType] = {
                    count: 0,
                    lastOccurrence: null
                };
            }
            this.stats.errors[errorType].count++;
            this.stats.errors[errorType].lastOccurrence = timestamp;
        }

        // 记录时间序列数据
        this.stats.timeSeries.push({
            timestamp,
            success,
            algorithm,
            duration
        });

        // 保持时间序列数据在24小时内
        const oneDayAgo = timestamp - (24 * 60 * 60 * 1000);
        this.stats.timeSeries = this.stats.timeSeries.filter(item => item.timestamp > oneDayAgo);

        this.saveStats();
        this.updateDisplay();
    }

    // 错误分类
    categorizeError(error) {
        if (error.includes('Invalid key')) return '密钥错误';
        if (error.includes('Invalid padding')) return '填充错误';
        if (error.includes('Malformed')) return '数据格式错误';
        if (error.includes('timeout')) return '超时错误';
        return '其他错误';
    }

    // 计算成功率
    getSuccessRate() {
        if (this.stats.totalRequests === 0) return 0;
        return Math.round((this.stats.successfulDecryptions / this.stats.totalRequests) * 100);
    }

    // 计算平均解密时间
    getAverageDecryptionTime() {
        const totalTime = Object.values(this.stats.algorithms)
            .reduce((sum, algo) => sum + algo.totalTime, 0);
        const totalAttempts = Object.values(this.stats.algorithms)
            .reduce((sum, algo) => sum + algo.count, 0);

        return totalAttempts > 0 ? Math.round(totalTime / totalAttempts) : 0;
    }

    // 获取最活跃的算法
    getMostActiveAlgorithm() {
        let maxCount = 0;
        let mostActive = '雪花算法';

        Object.entries(this.stats.algorithms).forEach(([key, algo]) => {
            if (algo.count > maxCount) {
                maxCount = algo.count;
                mostActive = algo.name;
            }
        });

        return mostActive;
    }

    // 更新显示
    updateDisplay() {
        // 更新概览卡片
        document.getElementById('successRate').textContent = this.getSuccessRate() + '%';
        document.getElementById('totalRequests').textContent = this.stats.totalRequests;
        document.getElementById('avgTime').textContent = this.getAverageDecryptionTime() + 'ms';
        document.getElementById('activeAlgorithm').textContent = this.getMostActiveAlgorithm();

        // 更新算法统计表格
        this.updateAlgorithmStats();

        // 更新域名统计表格
        this.updateDomainStats();

        // 更新错误统计表格
        this.updateErrorStats();
    }

    // 更新算法统计表格
    updateAlgorithmStats() {
        const tbody = document.getElementById('algorithmStats');
        tbody.innerHTML = '';

        Object.entries(this.stats.algorithms).forEach(([key, algo]) => {
            const successRate = algo.count > 0 ? Math.round((algo.success / algo.count) * 100) : 0;
            const avgTime = algo.count > 0 ? Math.round(algo.totalTime / algo.count) : 0;
            const lastUsed = algo.lastUsed ? new Date(algo.lastUsed).toLocaleString() : '-';

            const row = `
                <tr>
                    <td>${algo.name}</td>
                    <td>${algo.count}</td>
                    <td>${algo.success}</td>
                    <td>${successRate}%</td>
                    <td>${avgTime}ms</td>
                    <td>${lastUsed}</td>
                </tr>
            `;
            tbody.innerHTML += row;
        });
    }

    // 更新域名统计表格
    updateDomainStats() {
        const tbody = document.getElementById('domainStats');
        tbody.innerHTML = '';

        if (Object.keys(this.stats.domains).length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="5" style="text-align: center; color: #9cdcfe;">
                        暂无数据
                    </td>
                </tr>
            `;
            return;
        }

        Object.entries(this.stats.domains).forEach(([domain, stats]) => {
            const successRate = stats.requests > 0 ? Math.round((stats.success / stats.requests) * 100) : 0;
            const mainAlgorithm = Object.entries(stats.algorithms)
                .sort(([, a], [, b]) => b - a)[0];
            const mainAlgorithmName = mainAlgorithm ?
                this.stats.algorithms[mainAlgorithm[0]]?.name || mainAlgorithm[0] : '-';

            const row = `
                <tr>
                    <td>${domain}</td>
                    <td>${stats.requests}</td>
                    <td>${stats.success}</td>
                    <td>${successRate}%</td>
                    <td>${mainAlgorithmName}</td>
                </tr>
            `;
            tbody.innerHTML += row;
        });
    }

    // 更新错误统计表格
    updateErrorStats() {
        const tbody = document.getElementById('errorStats');
        tbody.innerHTML = '';

        if (Object.keys(this.stats.errors).length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="4" style="text-align: center; color: #9cdcfe;">
                        暂无错误记录
                    </td>
                </tr>
            `;
            return;
        }

        const totalErrors = Object.values(this.stats.errors)
            .reduce((sum, error) => sum + error.count, 0);

        Object.entries(this.stats.errors).forEach(([errorType, error]) => {
            const percentage = totalErrors > 0 ? Math.round((error.count / totalErrors) * 100) : 0;
            const lastOccurrence = error.lastOccurrence ?
                new Date(error.lastOccurrence).toLocaleString() : '-';

            const row = `
                <tr>
                    <td>${errorType}</td>
                    <td>${error.count}</td>
                    <td>${percentage}%</td>
                    <td>${lastOccurrence}</td>
                </tr>
            `;
            tbody.innerHTML += row;
        });
    }

    // 保存统计到存储
    saveStats() {
        chrome.storage.local.set({ 'decryptionStats': this.stats }, () => {
            if (chrome.runtime.lastError) {
                console.error('保存统计失败:', chrome.runtime.lastError);
            }
        });
    }

    // 从存储加载统计
    loadStats() {
        chrome.storage.local.get(['decryptionStats'], (result) => {
            if (result.decryptionStats) {
                this.stats = { ...this.stats, ...result.decryptionStats };
            }
        });
    }

    // 清空统计
    clearStats() {
        if (confirm('确定要清空所有统计数据吗？此操作不可恢复。')) {
            this.stats = {
                totalRequests: 0,
                successfulDecryptions: 0,
                failedDecryptions: 0,
                algorithms: {
                    'timestamp-traceid': { name: '雪花算法', count: 0, success: 0, totalTime: 0, lastUsed: null },
                    'uuid-based': { name: '冒泡算法', count: 0, success: 0, totalTime: 0, lastUsed: null },
                    'custom-logic': { name: '线性算法', count: 0, success: 0, totalTime: 0, lastUsed: null }
                },
                domains: {},
                errors: {},
                timeSeries: []
            };
            this.saveStats();
            this.updateDisplay();
        }
    }

    // 重置统计
    resetStats() {
        if (confirm('确定要重置统计数据吗？')) {
            this.loadStats();
            this.updateDisplay();
        }
    }

    // 导出统计数据
    exportStats() {
        const exportData = {
            exportTime: new Date().toISOString(),
            stats: this.stats,
            summary: {
                successRate: this.getSuccessRate(),
                totalRequests: this.stats.totalRequests,
                averageTime: this.getAverageDecryptionTime(),
                mostActiveAlgorithm: this.getMostActiveAlgorithm()
            }
        };

        const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `decryption-stats-${new Date().toISOString().split('T')[0]}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }

    // 开始自动刷新
    startAutoRefresh() {
        setInterval(() => {
            this.updateDisplay();
        }, 5000); // 每5秒刷新一次
    }
}

// 全局函数
function refreshStats() {
    if (window.decryptionStats) {
        window.decryptionStats.loadStats();
        window.decryptionStats.updateDisplay();
    }
}

function exportStats() {
    if (window.decryptionStats) {
        window.decryptionStats.exportStats();
    }
}

function clearStats() {
    if (window.decryptionStats) {
        window.decryptionStats.clearStats();
    }
}

function resetStats() {
    if (window.decryptionStats) {
        window.decryptionStats.resetStats();
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    window.decryptionStats = new DecryptionStats();
});

// 监听来自panel.js的统计更新消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === 'DECRYPTION_ATTEMPT' && window.decryptionStats) {
        window.decryptionStats.recordDecryptionAttempt(
            message.algorithm,
            message.success,
            message.duration,
            message.domain,
            message.error
        );
    }
});
